<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, StarFilled } from '@element-plus/icons-vue'
import { student_auth_api } from '@/api/student/student_login'
import { useRouter } from 'vue-router'

const formRef = ref(null)
const editMode = ref(false)
const loading = ref(false)
const router = useRouter()

// 添加收藏数据
const collectionsLoading = ref(false)
const collections = ref([])

// 添加收藏数据获取方法
const fetchCollections = async () => {
    try {
        collectionsLoading.value = true
        const studentId = getStuId()

        if (!studentId) {
            return
        }

        // 获取用户名
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        const username = studentInfo.username || studentInfo.stu_id

        console.log('尝试获取收藏数据，用户名:', username)

        // 尝试多个可能的API路径
        const apiPaths = [
            `/api/student/ai-collections/?username=${username}`,  // 首选路径
            `/api/student/collections/?username=${username}`,     // 备选路径1
            `/api/student/ai/collections/?username=${username}`   // 备选路径2
        ];

        let success = false;

        // 依次尝试不同的API路径
        for (const apiPath of apiPaths) {
            try {
                console.log('尝试从API路径获取数据:', apiPath);
                const response = await fetch(apiPath, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    // 设置较短的超时时间，避免长时间等待
                    signal: AbortSignal.timeout(3000)
                });

                // 检查响应状态
                if (!response.ok) {
                    console.warn(`API ${apiPath} 返回错误状态: ${response.status}`);
                    continue; // 尝试下一个API路径
                }

                const data = await response.json();

                // 处理收藏数据，只需要标题，限制为4项
                collections.value = data.slice(0, 4).map(item => ({
                    id: item.id,
                    title: item.title || '未命名收藏'
                }));

                console.log('成功获取收藏数据:', collections.value);
                success = true;
                break; // 成功获取数据，跳出循环
            } catch (apiError) {
                console.warn(`尝试 ${apiPath} 失败:`, apiError);
                // 继续尝试下一个API路径
            }
        }

        // 如果所有API路径都失败，使用本地存储或默认数据
        if (!success) {
            console.log('所有API请求失败，检查本地存储');

            // 尝试从localStorage获取缓存的收藏数据
            try {
                const cachedCollections = localStorage.getItem('cachedCollections');
                if (cachedCollections) {
                    collections.value = JSON.parse(cachedCollections);
                    console.log('使用本地缓存的收藏数据');
                    return;
                }
            } catch (cacheError) {
                console.error('读取本地缓存失败:', cacheError);
            }

            // 使用默认收藏数据，限制为4项
            console.log('使用默认收藏数据');
            collections.value = [
                { id: 1, title: '数据结构中的树和图' },
                { id: 2, title: '机器学习算法比较' },
                { id: 3, title: '操作系统内存管理' },
                { id: 4, title: '数据库事务特性' }
            ];
        } else {
            // 成功获取数据，缓存到localStorage
            try {
                localStorage.setItem('cachedCollections', JSON.stringify(collections.value));
            } catch (cacheError) {
                console.warn('缓存收藏数据失败:', cacheError);
            }
        }
    } catch (error) {
        console.error('获取收藏数据处理失败:', error);
        // 使用默认收藏数据，不显示错误消息给用户，限制为4项
        collections.value = [
            { id: 1, title: '数据结构中的树和图' },
            { id: 2, title: '机器学习算法比较' },
            { id: 3, title: '操作系统内存管理' },
            { id: 4, title: '数据库事务特性' }
        ];
    } finally {
        collectionsLoading.value = false;
    }
}

// 跳转到收藏页面
const goToCollections = () => {
    router.push('/student/record/collect')
}

const getStuId = () => {
  try {
    const rawInfo = localStorage.getItem('studentUserInfo')
    if (!rawInfo) throw new Error('无登录信息')

    const userInfo = JSON.parse(rawInfo)
    if (!userInfo?.stu_id) {
      localStorage.removeItem('studentUserInfo')
      router.push('/student/login')
      return null
    }
    return userInfo.stu_id
  } catch (e) {
    console.error('学生ID获取失败:', e)
    return null
  }
}

defineExpose({
  getStuId
})

// 定义默认的表单数据
const userData = reactive({
  name: '',
  gender: '',
  phone: '',
  address: '',
  email: '',
  hobbies: []
})

// 获取profile和更新profile的API引用
const getProfile = student_auth_api.getInfo
const updateProfile = student_auth_api.updateInfo

//验证规则
const rules = reactive({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '请输入住址', trigger: 'blur' },
        { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
    ]
})

// 切换编辑模式方法
const toggleEditMode = async () => {
    if (!editMode.value) {
        // 进入编辑模式时缓存原始数据
        originalData.value = JSON.parse(JSON.stringify(userData))
    } else {
        // 取消编辑时提示确认
        try {
            await ElMessageBox.confirm('确定要取消编辑吗？未保存的修改将会丢失。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '继续编辑',
                type: 'warning'
            })
            // 用户确认取消，恢复原始数据
        Object.assign(userData, originalData.value)
            editMode.value = false
        } catch {
            // 用户选择继续编辑，不做任何操作
        }
    }
    editMode.value = !editMode.value
}

// 初始化方法
const initFormData = (data) => {
    if (!data) {
        ElMessage.warning('获取用户数据失败')
        return
    }

    // 确保hobby字段处理正确
    let hobbies = data.hobby || []

    // 如果hobby是字符串，尝试解析它
    if (typeof hobbies === 'string') {
  try {
            hobbies = JSON.parse(hobbies)
        } catch (e) {
            console.error('解析hobby数据失败:', e)
            hobbies = []
        }
    }

    Object.assign(userData, {
        name: data.stu_name || '',
        gender: data.stu_gender || '',
        phone: data.stu_tel || '',
        address: data.stu_address || '',
        email: data.stu_email || '',
        hobbies: Array.isArray(hobbies) ? hobbies : []
    })

    console.log('初始化用户数据:', userData)
}

// 重置表单
const resetForm = async () => {
  try {
    if (editMode.value) {
      // 仅当在编辑模式时从服务器重载数据
      const data = await getProfile({ stu_id: getStuId() })
      initFormData(data)
    }
    formRef.value.resetFields()
  } catch (error) {
    ElMessage.error('重置失败：' + error.message)
  }
}

// 增加原始数据缓存
const originalData = ref(null)

//  提交表单
// 在submitForm方法中添加防抖
const isSubmitting = ref(false)

const submitForm = async () => {
  if (isSubmitting.value) return
  isSubmitting.value = true
    loading.value = true

  try {
    await formRef.value.validate()

    const stu_id = getStuId()
    if (!stu_id) {
            ElMessage.error('用户未登录或登录已过期')
      return
    }

        // 构建payload，确保所有字段符合后端期望格式
    const payload = {
            stu_id: stu_id,
      stu_name: userData.name,
            stu_gender: userData.gender, // 性别值必须是 'male', 'female', 'other' 之一
      stu_tel: userData.phone,
      stu_address: userData.address,
      stu_email: userData.email,
            // 后端会自动将hobby数据JSON化，所以直接使用数组
      hobby: userData.hobbies || []
    }

        // 打印详细的请求信息
        console.log('提交的个人资料数据:', payload)
        console.log('请求URL:', '/api/student/profile/')
        console.log('请求方法:', 'PUT')

        // 发送请求
        const response = await updateProfile(payload)
        console.log('服务器响应:', response)

        const data = response.data || response
    ElMessage.success(data?.message || '资料更新成功')
    editMode.value = false

    // 更新本地缓存数据
    originalData.value = JSON.parse(JSON.stringify(userData))
  } catch (error) {
        console.error('提交个人资料错误:', error)

        // 打印详细的错误信息
        if (error.response?.data) {
            console.error('服务器返回的错误信息:', error.response.data)

            // 如果有具体的字段错误，显示详细的错误信息
            if (error.response.data.errors) {
                const errorsObj = error.response.data.errors
                const errorMsg = Object.entries(errorsObj)
                    .map(([field, msg]) => `${field}: ${msg}`)
                    .join('\n')
                ElMessage.error(`表单验证失败:\n${errorMsg}`)
                return
            }
        }

    if (error.message.includes('Network Error')) {
      ElMessage.error('网络连接异常，请检查网络后重试')
    } else if (error.response?.status === 401) {
      ElMessage.error('登录状态已过期，请重新登录')
      localStorage.removeItem('studentUserInfo')
            router.push('/login')
        } else if (error.message) {
            ElMessage.error(error.message)
    } else {
            ElMessage.error('操作失败，请稍后重试')
    }
  } finally {
    loading.value = false
    isSubmitting.value = false
  }
}

// 修改onMounted生命周期钩子
onMounted(async () => {
    try {
        loading.value = true
        ElMessage.info('正在加载个人资料...')

        const studentUserInfo = localStorage.getItem('studentUserInfo')
        const userInfo = studentUserInfo ? JSON.parse(studentUserInfo) : null
        const stu_id = userInfo?.stu_id

        if (!stu_id) {
            throw new Error('未找到用户信息')
        }

        // 并行请求个人资料和收藏数据
        await Promise.all([
            (async () => {
                const data = await getProfile({ stu_id })
                initFormData(data)
                originalData.value = JSON.parse(JSON.stringify(userData))
            })(),
            fetchCollections()
        ])
    } catch (error) {
        ElMessage.error('获取资料失败：' + (error.message || '未知错误'))
        console.error('获取个人资料失败:', error)
    } finally {
        loading.value = false
    }
})

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
    <div class="profile-container">
        <el-card class="box-card" v-loading="loading">
            <template #header>
                <div class="card-header">
                    <span>个人资料</span>
                    <el-button
                        type="primary"
                        @click="toggleEditMode"
                        :loading="isSubmitting"
                    >
                        {{ editMode ? '取消' : '编辑资料' }}
                    </el-button>
                </div>
            </template>

            <el-form
                :model="userData"
                :rules="rules"
                ref="formRef"
                label-width="120px"
                :disabled="!editMode"
                status-icon
            >
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="userData.name" :disabled="!editMode" />
                </el-form-item>

                <el-form-item label="性别" prop="gender">
                    <el-select
                        v-model="userData.gender"
                        :disabled="!editMode"
                        placeholder="请选择性别"
                    >
                        <el-option label="男" value="male" />
                        <el-option label="女" value="female" />
                        <el-option label="其他" value="other" />
                    </el-select>
                </el-form-item>

                <el-form-item label="联系方式" prop="phone">
                    <el-input v-model="userData.phone" :disabled="!editMode" />
                </el-form-item>

                <el-form-item label="住址" prop="address">
                    <el-input v-model="userData.address" :disabled="!editMode" />
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userData.email" :disabled="!editMode" />
                </el-form-item>

                <el-form-item label="兴趣爱好" prop="hobbies">
                    <el-input-tag
                        v-model="userData.hobbies"
                        :disabled="!editMode"
                        placeholder="添加兴趣标签"
                    />
                </el-form-item>

                <el-form-item v-if="editMode">
                    <el-button
                        type="primary"
                        :loading="isSubmitting"
                        @click="submitForm"
                    >
                        <el-icon v-if="!isSubmitting"><Check /></el-icon>
                        {{ isSubmitting ? '提交中...' : '保存修改' }}
                    </el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 添加收藏展示卡片 -->
        <el-card class="box-card collections-card" v-loading="collectionsLoading">
            <template #header>
                <div class="card-header">
                    <span>我的收藏</span>
                    <el-button type="primary" @click="goToCollections">
                        查看全部
                    </el-button>
                </div>
            </template>

            <div v-if="collections.length === 0" class="empty-collections">
                <el-empty description="暂无收藏内容" />
            </div>
            <div v-else class="collections-list">
                <div v-for="(item, index) in collections" :key="index" class="collection-item">
                    <el-icon><StarFilled /></el-icon>
                    <span class="collection-title">{{ item.title }}</span>
                </div>
            </div>
        </el-card>
    </div>
<!--    <div class="chat-bubble" @click="toggleChat">-->
<!--        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">-->
<!--    </div>-->

<!--    <div class="chat-container" id="chatContainer">-->
<!--        <iframe src="http://121.40.242.43/chatbot/c7ZSvPxvxyO1fuIo" class="chat-iframe"></iframe>-->
<!--    </div>-->
</template>

<style scoped>
.profile-container {
    width: auto;
    height: auto;
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.collections-card {
    margin-top: 20px;
}

.collections-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 5px;
    max-height: 250px;
    overflow-y: auto;
}

.collection-item {
    display: flex;
    align-items: center;
    padding: 8px;
    border-radius: 4px;
    background-color: #f5f7fa;
}

.collection-title {
    margin-left: 8px;
    font-size: 14px;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: calc(100% - 30px);
}

.empty-collections {
    padding: 20px 0;
}

.el-input,
.el-select {
    width: 100%;
}

.el-form-item.is-error .el-input__inner {
    border-color: #f56c6c;
}

.el-form-item.is-success .el-input__inner {
    border-color: #67c23a;
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
